package com.taocyb.framework.security.captcha.kaptcha;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import com.google.code.kaptcha.text.WordRenderer;
import com.google.code.kaptcha.util.Configurable;

/**
 * 验证码文本字符渲染
 */
public class DefaultWordRenderer extends Configurable implements WordRenderer {

    
    private static List<Integer> HEIGHT = new ArrayList<Integer>(3); //高度配置
    static {
        HEIGHT.add(-1);
        HEIGHT.add(1);
        HEIGHT.add(0);
    }
    
    public BufferedImage renderWord(String word, int width, int height) {
        int fontSize = getConfig().getTextProducerFontSize();

        Color color = getConfig().getTextProducerFontColor();
        int charSpace = getConfig().getTextProducerCharSpace();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2D = image.createGraphics();
        g2D.setColor(color);

        RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
        g2D.setRenderingHints(hints);

        FontRenderContext frc = g2D.getFontRenderContext();
        Random random = new Random();

        int startPosY = (height - fontSize)/6 + fontSize;

        char[] wordChars = word.toCharArray();
        Font[] chosenFonts = new Font[wordChars.length];
        int[] charWidths = new int[wordChars.length];
        int widthNeeded = 0;
        int len = KaptchaUtils.FONTS.length;
        for (int i = 0; i < wordChars.length; i++) {
            if(i==0){
               chosenFonts[i] = KaptchaUtils.FIRST_FONT;
            }else{
               chosenFonts[i] = KaptchaUtils.FONTS[random.nextInt(len)];
            }
            char[] charToDraw = new char[] { wordChars[i] };
            GlyphVector gv = chosenFonts[i].createGlyphVector(frc, charToDraw);
            charWidths[i] = (int) gv.getVisualBounds().getWidth();
            widthNeeded = widthNeeded + charWidths[i];
        }

        int startPosX = (width - widthNeeded)/4;
        Collections.shuffle(HEIGHT,random);
        for (int i = 0; i < wordChars.length; i++) {
            g2D.setFont(chosenFonts[i]);
            char[] charToDraw = new char[] { wordChars[i] };
            if(i==0){
                g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY);
            }else{
                g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY+HEIGHT.get(i-1));
            }
            startPosX = startPosX + (int) charWidths[i] + charSpace;
        }
        return image;
    }
}
